import tkinter as tk
from tkinter import ttk, messagebox
import customtkinter
from ui.styles.theme import Theme
from core.utils.logger import debug, info

class RoleSwitcher(customtkinter.CTkFrame):
    """角色切换组件"""
    
    def __init__(self, parent, controller):
        super().__init__(parent, fg_color="transparent")
        self.controller = controller
        self.create_widgets()
    
    def create_widgets(self):
        # 当前角色指示器
        self.role_label = customtkinter.CTkLabel(
            self, 
            text="", 
            font=("Arial", 10),
            text_color=Theme.get_color('fg_secondary')
        )
        self.role_label.pack(side="left", padx=5)
        
        # 切换按钮
        self.switch_btn = customtkinter.CTkButton(
            self,
            text="Switch Mode",
            command=self.show_role_menu,
            width=100,
            height=32,
            font=('Arial', 11, 'bold'),
            fg_color=Theme.get_color('accent'),
            hover_color=Theme.get_color('accent_hover'),
            corner_radius=8
        )
        self.switch_btn.pack(side="left", padx=5)
        
        # 初始化显示
        self.update_display()
    
    def update_display(self):
        """更新显示"""
        user = self.controller.auth_service.current_user
        if user and len(user.get_roles()) > 1:
            # 显示当前角色
            role_text = self._get_role_text(user.current_role)
            self.role_label.configure(text=f"Current Mode: {role_text}")
            self.pack()  # 显示组件
        else:
            self.pack_forget()  # 隐藏组件
    
    def show_role_menu(self):
        """显示角色切换菜单"""
        user = self.controller.auth_service.current_user
        if not user:
            return
        
        # 创建弹出菜单
        menu = tk.Menu(self, tearoff=0)
        
        for role in user.get_roles():
            if role != user.current_role:
                menu.add_command(
                    label=f"Switch to {self._get_role_text(role)}",
                    command=lambda r=role: self.switch_to_role(r)
                )
        
        # 显示菜单
        try:
            menu.post(self.switch_btn.winfo_rootx(), 
                     self.switch_btn.winfo_rooty() + self.switch_btn.winfo_height())
        except tk.TclError:
            # 如果无法显示菜单，使用消息框
            self.show_role_dialog()
    
    def show_role_dialog(self):
        """显示角色切换对话框（备用方案）"""
        user = self.controller.auth_service.current_user
        if not user:
            return
        
        available_roles = [role for role in user.get_roles() if role != user.current_role]
        if not available_roles:
            return
        
        # 创建选择对话框
        dialog = customtkinter.CTkToplevel(self.controller)
        dialog.title("Switch Mode")
        dialog.geometry("350x250")
        dialog.resizable(False, False)
        
        # 居中显示
        dialog.transient(self.controller)
        dialog.grab_set()
        
        # 主容器
        main_frame = customtkinter.CTkFrame(dialog, fg_color="transparent")
        main_frame.pack(fill='both', expand=True, padx=30, pady=30)
        
        # 标题
        title_label = customtkinter.CTkLabel(
            main_frame, 
            text="Select Mode to Switch", 
            font=("Arial", 16, "bold"),
            text_color=Theme.get_color('fg_primary')
        )
        title_label.pack(pady=(0, 20))
        
        # 内容容器
        content_frame = customtkinter.CTkFrame(main_frame, fg_color="transparent")
        content_frame.pack(fill='both', expand=True)
        
        # 角色选择
        role_var = tk.StringVar(value=available_roles[0])
        for role in available_roles:
            radio = customtkinter.CTkRadioButton(
                content_frame,
                text=self._get_role_text(role),
                variable=role_var,
                value=role,
                font=('Arial', 13),
                text_color=Theme.get_color('fg_primary')
            )
            radio.pack(anchor='w', pady=10, padx=20)
        
        # 按钮
        button_frame = customtkinter.CTkFrame(main_frame, fg_color="transparent")
        button_frame.pack(pady=(20, 0))
        
        customtkinter.CTkButton(
            button_frame,
            text="Switch",
            command=lambda: self.switch_to_role(role_var.get(), dialog),
            width=120,
            height=35,
            font=('Arial', 13, 'bold'),
            fg_color=Theme.get_color('accent'),
            hover_color=Theme.get_color('accent_hover'),
            corner_radius=8
        ).pack(side="left", padx=5)
        
        customtkinter.CTkButton(
            button_frame,
            text="Cancel",
            command=dialog.destroy,
            width=120,
            height=35,
            font=('Arial', 13),
            fg_color=("gray70", "gray30"),
            hover_color=("gray60", "gray40"),
            corner_radius=8
        ).pack(side="left", padx=5)
    
    def switch_to_role(self, role, dialog=None):
        """切换角色"""
        if dialog:
            dialog.destroy()
        
        # 如果需要切换到管理员模式，需要验证密码
        if role == "admin" and self.controller.auth_service.current_user:
            if not self._verify_admin_password():
                return
        
        if self.controller.auth_service.switch_user_role(role):
            self.update_display()
            
            # 根据角色跳转到相应页面
            if role == "admin":
                self.controller.show_page("AdminPage")
            else:
                self.controller.show_page("ProductPage")
            
            from core.utils.i18n import t
            messagebox.showinfo(
                t("role.switch.success"),
                t("role.switch.success_message", role=self._get_role_text(role))
            )
        else:
            from core.utils.i18n import t
            messagebox.showerror(
                t("role.switch.failed"),
                t("role.switch.failed_message", role=self._get_role_text(role))
            )
    
    def _verify_admin_password(self):
        """验证管理员密码"""
        from core.utils.i18n import t
        
        # 创建密码输入对话框
        dialog = customtkinter.CTkToplevel(self.controller)
        dialog.title(t("admin.login.title"))
        dialog.geometry("400x250")
        dialog.resizable(False, False)
        
        # 居中显示
        dialog.transient(self.controller)
        dialog.grab_set()
        
        # 主容器
        main_frame = customtkinter.CTkFrame(dialog, fg_color="transparent")
        main_frame.pack(fill='both', expand=True, padx=30, pady=30)
        
        # 标题
        title_label = customtkinter.CTkLabel(
            main_frame, 
            text="⚠️ Admin Verification", 
            font=("Arial", 16, "bold"),
            text_color=Theme.get_color('warning')
        )
        title_label.pack(pady=(0, 20))
        
        # 说明文字
        info_label = customtkinter.CTkLabel(
            main_frame,
            text="For security, please enter the admin verification code to switch to admin mode",
            font=("Arial", 11),
            text_color=Theme.get_color('fg_secondary'),
            wraplength=300,
            justify="center"
        )
        info_label.pack(pady=(0, 20))
        
        # 密码输入框
        password_frame = customtkinter.CTkFrame(main_frame, fg_color="transparent")
        password_frame.pack(fill='x', pady=10)
        
        password_label = customtkinter.CTkLabel(
            password_frame,
            text="Verification Code：",
            font=('Arial', 12),
            text_color=Theme.get_color('fg_primary')
        )
        password_label.pack(side='left', padx=(0, 10))
        
        self.password_entry = customtkinter.CTkEntry(
            password_frame,
            placeholder_text="Enter admin verification code",
            show="*",
            width=220,
            height=35,
            font=('Arial', 12)
        )
        self.password_entry.pack(side='left')
        self.password_entry.focus()
        self.password_entry.bind('<Return>', lambda e: self._confirm_password(dialog))
        
        # 按钮
        button_frame = customtkinter.CTkFrame(main_frame, fg_color="transparent")
        button_frame.pack(pady=(20, 0))
        
        customtkinter.CTkButton(
            button_frame,
            text=t("common.confirm"),
            command=lambda: self._confirm_password(dialog),
            width=120,
            height=35,
            font=('Arial', 13, 'bold'),
            fg_color=Theme.get_color('accent'),
            hover_color=Theme.get_color('accent_hover'),
            corner_radius=8
        ).pack(side="left", padx=5)
        
        customtkinter.CTkButton(
            button_frame,
            text=t("common.cancel"),
            command=dialog.destroy,
            width=120,
            height=35,
            font=('Arial', 13),
            fg_color=("gray70", "gray30"),
            hover_color=("gray60", "gray40"),
            corner_radius=8
        ).pack(side="left", padx=5)
        
        # 等待对话框关闭
        self._password_verified = False
        dialog.wait_window()
        
        return self._password_verified
    
    def _confirm_password(self, dialog):
        """确认管理员验证码"""
        from core.utils.i18n import t
        
        verification_code = self.password_entry.get()
        if not verification_code:
            messagebox.showerror(t("common.error"), "Please enter the admin verification code")
            return
        
        # 验证管理员验证码（固定为admin2025）
        if verification_code == "admin2025":
            self._password_verified = True
            dialog.destroy()
        else:
            messagebox.showerror(t("common.error"), "Incorrect verification code, cannot switch to admin mode")
            self.password_entry.delete(0, tk.END)
            self.password_entry.focus()
    
    def _get_role_text(self, role):
        """获取角色显示文本"""
        role_map = {
            "customer": "Customer",
            "admin": "Admin",
            "seller": "Seller"
        }
        return role_map.get(role, role)
